/**
 * 
 * 起迪科技 Copyright (c) 2014-2018 QiDi,Inc.All Rights Reserved.
 */

package cn.qidisoft.edu.hzjt.controller.communityamateurschool;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.qidisoft.core.common.context.ApplicationContextConfigUtil;
import cn.qidisoft.core.common.log.LoggerAdapter;
import cn.qidisoft.core.common.log.LoggerAdapterFactory;
import cn.qidisoft.core.common.pagination.Page;
import cn.qidisoft.core.common.pagination.PaginationBean;
import cn.qidisoft.core.util.DateUtil;
import cn.qidisoft.core.util.file.FileUtil;
import cn.qidisoft.core.util.moffice.excel.ExpExcelUtil;
import cn.qidisoft.edu.hzjt.annotation.SysLogger;
import cn.qidisoft.edu.hzjt.constants.Constant;
import cn.qidisoft.edu.hzjt.controller.BaseController;
import cn.qidisoft.edu.hzjt.exception.RPCException;
import cn.qidisoft.edu.hzjt.model.BjxxClassMaterialFile;
import cn.qidisoft.edu.hzjt.model.CommunityAmateurSchool;
import cn.qidisoft.edu.hzjt.model.CommunityAmateurSchoolAtt;
import cn.qidisoft.edu.hzjt.model.CommunityAmateurSchoolStudent;
import cn.qidisoft.edu.hzjt.model.ResponseResult;
import cn.qidisoft.edu.hzjt.model.Student;
import cn.qidisoft.edu.hzjt.model.UserEmployee;
import cn.qidisoft.edu.hzjt.service.ICommunityAmateurSchoolAttService;
import cn.qidisoft.edu.hzjt.service.ICommunityAmateurSchoolService;
import cn.qidisoft.edu.hzjt.service.ICommunityAmateurSchoolStudentService;
import cn.qidisoft.edu.hzjt.service.zyc.IStudentService;
import cn.qidisoft.edu.hzjt.utils.LogType;

/**
 * 
 * 
 * @author Administrator
 * @version $Id: CommunityAmateurSchoolController.java, v 0.1 2018年11月1日 上午10:50:34 hhl Exp $
 */

@Controller
@RequestMapping(value = "communityAmateurSchool")
public class CommunityAmateurSchoolController {
    protected static final LoggerAdapter                        LOGGER = LoggerAdapterFactory
        .getLogger(LogType.HZJT_LOGGER.val);
    @Autowired
    private ICommunityAmateurSchoolService                      communityAmateurSchoolService;

    @Autowired
    private ICommunityAmateurSchoolAttService                   communityAmateurSchoolAttService;

    @Autowired
    private ICommunityAmateurSchoolStudentService               communityAmateurSchoolStudentService;

    @Autowired
    private IStudentService                                     studentService;

    private static Map<String, List<CommunityAmateurSchoolAtt>> picMap = new HashMap<String, List<CommunityAmateurSchoolAtt>>();

    private static String                                       upload = null;

    static {
        upload = ApplicationContextConfigUtil.getString("file.path", null);
    }

    @RequestMapping(value = "/index")
    public String index(ModelMap model, HttpServletRequest request) {
        try {
            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
            picMap.remove(userEmployee.getUserid());

            request.setAttribute("msg", BaseController.getParameter("msg"));
            BaseController.removeParameter("msg");
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
        return "communityAmateurSchool/communityAmateurSchoolList";
    }

    @RequestMapping(value = "/List")
    @ResponseBody
    public ResponseResult List(ModelMap model, HttpServletRequest request,
                               @RequestParam(value = "rows", required = false) String pageSize,
                               @RequestParam(value = "page", required = false) String currentPage,
                               CommunityAmateurSchool data) {

        try {
            Page page = new Page();
            page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
            page.setPageSize(pageSize == null ? Constant.PageSize : Integer.valueOf(pageSize));
            BaseController.setSortByColumn(request, "createtime", "desc");
            data.setOrderField((String) request.getAttribute("orderField"));
            data.setOrderFlag((String) request.getAttribute("orderFlag"));

            PaginationBean<CommunityAmateurSchool> paginationBean = communityAmateurSchoolService
                .queryPageList(data, page);
            ResponseResult result = new ResponseResult();
            if (paginationBean.getPageList().isEmpty()) {
                result.setRows(new ArrayList<CommunityAmateurSchool>());
            } else {
                result.setRows(paginationBean.getPageList());
            }
            result.setTotal(paginationBean.getTotalRecords());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }

    @RequestMapping(value = "/addInInt")
    public String add(ModelMap model, HttpServletRequest request) {
        try {
            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
            picMap.remove(userEmployee.getUserid());

            model.addAttribute("emid", userEmployee.getEmid());
            model.addAttribute("xm", userEmployee.getXm());
            model.addAttribute("zgh", userEmployee.getZgh());
            List<Student> selStudent = studentService.selStudent();
            request.setAttribute("students", selStudent);
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(selStudent);
            request.setAttribute("json", json);

            request.setAttribute("msg", BaseController.getParameter("msg"));
            BaseController.removeParameter("msg");
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
        return "communityAmateurSchool/add_CommunityAmateurSchool";
    }

    @RequestMapping(value = "/details")
    public String details(ModelMap model, HttpServletRequest request,
                          @RequestParam(value = "id", required = false) Integer id,
                          @RequestParam(value = "gid", required = false) String gid) {
        try {
            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
            picMap.remove(userEmployee.getUserid());

            CommunityAmateurSchool data = new CommunityAmateurSchool();
            data.setDxid(id);
            data.setGid(gid);
            data = communityAmateurSchoolService.queryByPK(data);
            model.addAttribute("data", data);
            model.addAttribute("xm", userEmployee.getXm());
            model.addAttribute("students", studentService.selStudent());
            CommunityAmateurSchoolStudent communityAmateurSchoolStudent = new CommunityAmateurSchoolStudent();
            communityAmateurSchoolStudent.setParentid(id);
            List<CommunityAmateurSchoolStudent> communityAmateurSchoolStudentList = communityAmateurSchoolStudentService
                .queryList(communityAmateurSchoolStudent);
            ObjectMapper mapper1 = new ObjectMapper();
            String dataJSON = mapper1.writeValueAsString(communityAmateurSchoolStudentList);
            request.setAttribute("deveAmateurSchoolStudentsJSON", dataJSON + "");
            // 获取附件信息
            CommunityAmateurSchoolAtt att = new CommunityAmateurSchoolAtt();
            att.setParentid(id);
            List<CommunityAmateurSchoolAtt> attList = communityAmateurSchoolAttService
                .queryList(att);
            request.setAttribute("dataList", attList);

            return "communityAmateurSchool/details_CommunityAmateurSchool";
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("查询 queryByPK [{}] error," + this.getClass().getName() + "=[{}]",
                this.getClass().getName(), e.getMessage());
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    @SysLogger(description = "团校管理信息", moduleName = "团校管理", method = "新增保存")
    @RequestMapping(value = "/add")
    public String add(ModelMap model, HttpServletRequest request, CommunityAmateurSchool data) {
        try {
            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
            data.setCreatorid(userEmployee.getUid());
            data.setCreatetime(new Date());
            data.setCreatorname(userEmployee.getName());
            communityAmateurSchoolService.add(data);

            /*   CommunityAmateurSchool data1 = new CommunityAmateurSchool();
            data1.setGid(gid);
            data1 = communityAmateurSchoolService.queryByPK(data);*/

            List<CommunityAmateurSchoolAtt> docFileResourceList = picMap
                .get(String.valueOf(userEmployee.getUserid()));
            if (docFileResourceList != null && !docFileResourceList.isEmpty()) {
                MultipartFile file = null;
                Integer orders = 0;
                for (CommunityAmateurSchoolAtt r : docFileResourceList) {
                    file = r.getMufile();
                    String name = file.getOriginalFilename();// 获取上传文件名
                    InputStream in = r.getInputStream();// 获取文件对象
                    int pos = name.lastIndexOf(".");
                    String lastname = name.substring(pos, name.length());
                    // 文件保存的路径
                    String savePath = upload + File.separator + Constant.CONTRIBUTIONATT_RESOURCE_TX
                                      + "/" + userEmployee.getUid() + "/"
                                      + DateUtil.formatDate2Str(new Date(), "yyyy-MM-dd")
                                      + File.separator + r.getGid();
                    FileUtil.saveFile(savePath, in, r.getGid() + lastname);
                    r.setParentid(data.getDxid());
                    r.setFileid(r.getGid());// 附件id
                    r.setFilename(name);
                    r.setOrders(orders);
                    communityAmateurSchoolAttService.add(r);
                    orders++;
                }
            }

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
        String action = request.getParameter("action");
        if (action.equals("1")) {
            return "redirect:details?id=" + data.getDxid();
        } else if (action.equals("2")) {
            return "redirect:addInInt";
        }
        return null;
    }

    @RequestMapping(value = "/updateToview", method = RequestMethod.GET)
    public String updateToview(ModelMap model, HttpServletRequest request,
                               @RequestParam(value = "id") Integer id) {
        try {
            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
            picMap.remove(userEmployee.getUserid());

            List<Student> selStudent = studentService.selStudent();
            request.setAttribute("students", selStudent);
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(selStudent);
            request.setAttribute("json", json);

            CommunityAmateurSchool data = new CommunityAmateurSchool();
            data.setDxid(id);
            data = communityAmateurSchoolService.queryByPK(data);
            model.addAttribute("das", data);
            model.addAttribute("xm", userEmployee.getXm());
            model.addAttribute("students", studentService.selStudent());

            CommunityAmateurSchoolStudent communityAmateurSchoolStudent = new CommunityAmateurSchoolStudent();
            communityAmateurSchoolStudent.setParentid(id);
            List<CommunityAmateurSchoolStudent> communityAmateurSchoolStudentList = communityAmateurSchoolStudentService
                .queryList(communityAmateurSchoolStudent);
            ObjectMapper mapper1 = new ObjectMapper();
            String dataJSON = mapper1.writeValueAsString(communityAmateurSchoolStudentList);
            request.setAttribute("deveAmateurSchoolStudentsJSON", dataJSON + "");

            // 获取附件信息
            CommunityAmateurSchoolAtt att = new CommunityAmateurSchoolAtt();
            att.setParentid(id);
            List<CommunityAmateurSchoolAtt> attList = communityAmateurSchoolAttService
                .queryList(att);
            request.setAttribute("dataList", attList);

            return "communityAmateurSchool/update_CommunityAmateurSchool";
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("查询 queryByPK [{}] error," + this.getClass().getName() + "=[{}]",
                this.getClass().getName(), e.getMessage());
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    @SysLogger(description = "团校管理信息", moduleName = "团校管理", method = "修改")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(ModelMap model, HttpServletRequest request, CommunityAmateurSchool data) {
        try {

            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
            communityAmateurSchoolService.update(data);

            List<CommunityAmateurSchoolAtt> docFileResourceList = picMap
                .get(String.valueOf(userEmployee.getUserid()));
            if (docFileResourceList != null && !docFileResourceList.isEmpty()) {
                MultipartFile file = null;
                Integer orders = 0;
                for (CommunityAmateurSchoolAtt r : docFileResourceList) {
                    file = r.getMufile();
                    String name = file.getOriginalFilename();// 获取上传文件名
                    InputStream in = r.getInputStream();// 获取文件对象
                    int pos = name.lastIndexOf(".");
                    String lastname = name.substring(pos, name.length());
                    // 文件保存的路径
                    String savePath = upload + File.separator + Constant.CONTRIBUTIONATT_RESOURCE_TX
                                      + "/" + userEmployee.getUid() + "/"
                                      + DateUtil.formatDate2Str(new Date(), "yyyy-MM-dd")
                                      + File.separator + r.getGid();
                    FileUtil.saveFile(savePath, in, r.getGid() + lastname);
                    r.setParentid(data.getDxid());
                    r.setFileid(r.getGid());// 附件id
                    r.setFilename(name);
                    r.setOrders(orders);
                    communityAmateurSchoolAttService.add(r);
                    orders++;
                }
            }
            return "redirect:index";
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("查询 update [{}] error," + this.getClass().getName() + "=[{}]",
                this.getClass().getName(), e.getMessage());
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    @SysLogger(description = "团校管理信息", moduleName = "团校管理", method = "删除")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public String delete(ModelMap model, HttpServletRequest request) {
        try {
            String[] idList = request.getParameter("idList").split(",");
            CommunityAmateurSchool data = new CommunityAmateurSchool();
            data.setIds(idList);
            communityAmateurSchoolService.delete(data);
            BaseController.setParameter("msg", "删除成功");
            return "redirect:index";
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("删除 delete [{}] error," + this.getClass().getName() + "=[{}]",
                this.getClass().getName(), e.getMessage());
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    /**
     * 上传附件
     * 
     * @param file
     * @param request
     * @param response
     */
    @RequestMapping(value = "/source_upload", method = RequestMethod.POST)
    public @ResponseBody void loadFile(@RequestParam("file") MultipartFile file,
                                       HttpServletRequest request, HttpServletResponse response) {

        List<CommunityAmateurSchoolAtt> list = new ArrayList<CommunityAmateurSchoolAtt>();
        UserEmployee userEmployee = (UserEmployee) request.getSession()
            .getAttribute(Constant.LOGIN_CONSOLE_USER);
        List<CommunityAmateurSchoolAtt> docFileResourceList = picMap
            .get(String.valueOf(userEmployee.getUserid()));
        // 本地env配置路径
        String path = Constant.UPLOADPATH;
        CommunityAmateurSchoolAtt docFile = new CommunityAmateurSchoolAtt();
        if (!file.isEmpty()) {
            // 文件的大小
            docFile
                .setFilesize(String.valueOf(FileUtil.FormetFileSize(Long.valueOf(file.getSize()))));

            String name = file.getOriginalFilename();// 获取上传文件名
            docFile.setFilename(name);
            String gid = UUID.randomUUID().toString();

            // 获取文件后缀名称
            String extend = FilenameUtils.getExtension(name);
            // 文件路径带后缀
            docFile.setFilepath(Constant.CONTRIBUTIONATT_RESOURCE_TX + "/" + userEmployee.getUid()
                                + "/" + DateUtil.formatDate2Str(new Date(), "yyyy-MM-dd") + "/"
                                + gid + "/" + gid + "." + extend);
            // 全路径系统文件名称带点
            docFile
                .setSysfilepath(path + File.separator + gid + File.separator + gid + "." + extend);
            // 文件名称uuid
            docFile.setFilename(gid);
            // 上传时间
            /* docFile.setMsubmittime(new Date()); */
            //获取文件扩展名
            docFile.setExtension(FileUtil.getFileExtendName(name).toLowerCase());
            //获取文件类型
            docFile.setContenttype(FileUtil.getFileExtendName(name).toLowerCase());
            docFile
                .setFilesize(String.valueOf(FileUtil.FormetFileSize(Long.valueOf(file.getSize()))));// 获取文件大小
            // uuid
            docFile.setGid(gid);

            docFile.setMufile(file);
            try {
                docFile.setInputStream(file.getInputStream());
            } catch (IOException e) {
            }

            if (docFileResourceList != null && docFileResourceList.size() > 0) {
                docFileResourceList.add(docFile);
                picMap.put(String.valueOf(userEmployee.getUserid()), docFileResourceList);
            } else {
                list.add(docFile);
                picMap.put(String.valueOf(userEmployee.getUserid()), list);
            }
            LOGGER.info("附件上传成功！");
        }
        PrintWriter writer = null;
        try {

            BjxxClassMaterialFile docFile2 = new BjxxClassMaterialFile();
            docFile2.setFilepath(docFile.getFilepath());
            // 文件名称
            docFile2.setFilename(docFile.getFilename());
            docFile2.setSysfilepath(docFile.getSysfilepath());

            writer = (PrintWriter) response.getWriter();
            String json = JSONObject.toJSONString(docFile2);
            writer.write(json);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 新增删除服务器的文件
     * 
     * @param request
     * @return
     */
    @RequestMapping(value = "/deletefile", method = RequestMethod.POST)
    public @ResponseBody Map<String, Object> deleteFile(HttpServletRequest request) {

        Map<String, Object> dataMap = new HashMap<String, Object>();
        try {
            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);

            // env配置路径
            String path = upload;

            String filepath = request.getParameter("filepath");
            LOGGER.info("文件的原始路径===" + filepath);
            // 文件的全路径
            String fullpath = null;
            // 文件名称
            String filename = null;
            // 文件名无后缀
            String fileNoSuffix = null;

            if (filepath.indexOf("prefix") == -1) {
                // 文件的文件名称
                fileNoSuffix = filepath.split(",")[0];
                String sec = filepath.split(",")[1];
                // 文件的后缀
                String suffix = sec.substring(sec.indexOf("."));
                // 文件名无后缀加上后缀
                filename = fileNoSuffix + suffix;
                // 文件的全路径
                fullpath = path + "/" + fileNoSuffix;
                // FileUtil.deleteFile(fullpath, filename);//删除文件目录下面的文件
                // FileUtils.forceDelete(new File(fullpath)); //删除文件目录
            } else {
                return dataMap;
            }

            List<CommunityAmateurSchoolAtt> noticeNewsFilepathList = picMap
                .get(String.valueOf(userEmployee.getUserid()));

            // 删除list里面前台删除的前台信息图片附件表
            if (noticeNewsFilepathList != null && !noticeNewsFilepathList.isEmpty()) {
                for (CommunityAmateurSchoolAtt noticenewsfilepath : noticeNewsFilepathList) {
                    if (noticenewsfilepath.getFilename().equals(fileNoSuffix)) {
                        noticeNewsFilepathList.remove(noticenewsfilepath);
                        break;
                    }
                }
            }
            // 先删除
            picMap.remove(userEmployee.getUserid());
            // 后添加
            picMap.put(String.valueOf(userEmployee.getUserid()), noticeNewsFilepathList);
            dataMap.put("success", "0000");
            return dataMap;
        } catch (Exception e) {
            dataMap.put("success", "-9999");
            return dataMap;
        }
    }

    /**
     * 修改删除图片
     * 
     * @param file
     * @param request
     * @param response
     */
    @RequestMapping(value = "/source_upload_update", method = RequestMethod.POST)
    public @ResponseBody Map<String, Object> source_upload_update(@RequestParam("id") String id,
                                                                  HttpServletRequest request,
                                                                  HttpServletResponse response) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        /*        UserEmployee userEmployee = (UserEmployee) request.getSession()
            .getAttribute(Constant.LOGIN_CONSOLE_USER);
        */ try {
            CommunityAmateurSchoolAtt data = new CommunityAmateurSchoolAtt();
            data.setFileid(id);
            data = communityAmateurSchoolAttService.queryByPK(data);
            communityAmateurSchoolAttService.delete(data);
            if (data != null) {
                String upload = Constant.UPLOADPATH;
                int idlength = data.getFileid().lastIndexOf("");
                int pos = data.getFilepath().lastIndexOf(".");
                String filepath = data.getFilepath().substring(0, pos - idlength - 1);
                File file = new File(upload + File.separator + filepath);
                if (file.isDirectory()) {//判断file是否是文件目录 若是返回TRUE  
                    String name[] = file.list();//name存储file文件夹中的文件名  
                    for (int i = 0; i < name.length; i++) {
                        File f = new File(upload + File.separator + filepath, name[i]);//此时就可得到文件夹中的文件  
                        f.delete();//删除文件  
                    }
                    FileUtils.forceDelete(new File(upload + File.separator + filepath)); //最后删除文件目录
                }
                // FileTool.deleteFile(file);
            }

            dataMap.put("success", "0000");
        } catch (Exception e) {
            LOGGER.error("调用services网络异常", e);
            dataMap.put("success", "-9999");
        }
        return dataMap;
    }

    /**
     * 下载
     * 
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/export")
    public @ResponseBody String export(HttpServletRequest request, HttpServletResponse response,
                                       CommunityAmateurSchool data,
                                       @RequestParam("bodyData") String bodyData,
                                       ModelMap model) throws Exception {
        try {

            BaseController.setSortByColumn(request, "createtime", "desc");
            data.setOrderField((String) request.getAttribute("orderField"));
            data.setOrderFlag((String) request.getAttribute("orderFlag"));
            List<CommunityAmateurSchool> datalist = communityAmateurSchoolService.export(data);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String[][] title_name = { { "团校期数", "授课主题", "授课时间", "授课地点", "计划参与人数", "实际授课人数",
                                        "创建时间" } };
            String[] title_style = { "hwzs_16_bold_25", "kt_12_bold_18", "st_12_r_20", "st_12_n_20",
                                     "st_12_n_20", "st_12_n_20" };
            String fileName = "团校管理信息";
            String[] remark = { "" };
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            /*   List<CommunityAmateurSchool> datalist = JSONArray.parseArray(bodyData,
                CommunityAmateurSchool.class);*/
            if (datalist != null && !datalist.isEmpty()) {
                for (CommunityAmateurSchool r : datalist) {
                    Map<String, Object> map = new LinkedHashMap<String, Object>();
                    map.put("dxqs", r.getDxqs());
                    map.put("skzt", r.getSkzt());
                    map.put("sksj", r.getSksj());
                    map.put("skdd", r.getSkdd());
                    map.put("jhcyrs", r.getJhcyrs());
                    map.put("sjskrs", r.getSjskrs());
                    map.put("cjsj", sdf.format(r.getCreatetime()));
                    list.add(map);
                }
            }
            HSSFWorkbook wb = ExpExcelUtil.getWorkBookExcel(title_name, title_style, 100, remark,
                fileName, list);
            try {
                String filenameConvert = "团校管理信息";/* new String(fileName.getBytes("GB2312"), "ISO8859-1"); */
                response.reset();
                response.setContentType("application/vnd.ms-excel;charset=utf-8");
                response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String((filenameConvert + ".xls").getBytes(),
                        "iso-8859-1"));
                response.setDateHeader("Expires", 0);
                ServletOutputStream os = response.getOutputStream();
                wb.write(os);
                os.flush();
            } catch (Exception e) {
                System.out.println("网络连接断开，可能用户取消了导出");
                model.addAttribute(Constant.EXPTION_MSG_KEY, e);
                return "error/error";
            }
        } catch (RPCException e) {
            LOGGER.error("获得信息 export[{}] error," + this.getClass().getName() + "=[{}]",
                this.getClass().getName(), e.getMessage());
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
        return null;
    }

    /**************************************************************************************************/
    /**
     * 学生端
     * 
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/index_Student")
    public String index_Student(ModelMap model, HttpServletRequest request) {
        try {

        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
        return "communityAmateurSchool/communityAmateurSchoolList_Student";
    }

    @RequestMapping(value = "/List_Student")
    @ResponseBody
    public ResponseResult List_Student(ModelMap model, HttpServletRequest request,
                                       @RequestParam(value = "rows", required = false) String pageSize,
                                       @RequestParam(value = "page", required = false) String currentPage,
                                       CommunityAmateurSchool data) {
        try {

            Student student = (Student) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
            CommunityAmateurSchoolStudent communityAmateurSchoolStudent = new CommunityAmateurSchoolStudent();
            communityAmateurSchoolStudent.setXsid(student.getXsid());
            List<CommunityAmateurSchoolStudent> communityAmateurSchoolStudentList = communityAmateurSchoolStudentService
                .queryList_Student(communityAmateurSchoolStudent);

            if (communityAmateurSchoolStudentList != null
                && !communityAmateurSchoolStudentList.isEmpty()) {
                Integer[] parentid = new Integer[communityAmateurSchoolStudentList.size()];
                int i = 0;
                for (CommunityAmateurSchoolStudent s : communityAmateurSchoolStudentList) {
                    parentid[i] = s.getParentid();
                    i++;
                }
                data.setDxids(parentid);
                Page page = new Page();
                page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
                page.setPageSize(pageSize == null ? Constant.PageSize : Integer.valueOf(pageSize));
                BaseController.setSortByColumn(request, "createtime", "desc");
                data.setOrderField((String) request.getAttribute("orderField"));
                data.setOrderFlag((String) request.getAttribute("orderFlag"));

                PaginationBean<CommunityAmateurSchool> paginationBean = communityAmateurSchoolService
                    .queryPageList(data, page);
                ResponseResult result = new ResponseResult();
                if (paginationBean.getPageList().isEmpty()) {
                    result.setRows(new ArrayList<CommunityAmateurSchool>());
                } else {
                    result.setRows(paginationBean.getPageList());
                }
                result.setTotal(paginationBean.getTotalRecords());
                return result;
            } else {
                ResponseResult result = new ResponseResult();
                result.setRows(new ArrayList<CommunityAmateurSchool>());
                result.setTotal(0);
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }

    @RequestMapping(value = "/details_Student")
    public String details_Student(ModelMap model, HttpServletRequest request,
                                  @RequestParam(value = "id", required = false) Integer id) {
        try {

            CommunityAmateurSchool data = new CommunityAmateurSchool();
            data.setDxid(id);
            data = communityAmateurSchoolService.queryByPK(data);
            model.addAttribute("data", data);

            model.addAttribute("students", studentService.selStudent());
            CommunityAmateurSchoolStudent communityAmateurSchoolStudent = new CommunityAmateurSchoolStudent();
            communityAmateurSchoolStudent.setParentid(id);
            List<CommunityAmateurSchoolStudent> communityAmateurSchoolStudentList = communityAmateurSchoolStudentService
                .queryList(communityAmateurSchoolStudent);
            ObjectMapper mapper1 = new ObjectMapper();
            String dataJSON = mapper1.writeValueAsString(communityAmateurSchoolStudentList);
            request.setAttribute("deveAmateurSchoolStudentsJSON", dataJSON + "");
            // 获取附件信息
            CommunityAmateurSchoolAtt att = new CommunityAmateurSchoolAtt();
            att.setParentid(id);
            List<CommunityAmateurSchoolAtt> attList = communityAmateurSchoolAttService
                .queryList(att);
            request.setAttribute("dataList", attList);

            return "communityAmateurSchool/details_CommunityAmateurSchool_Student";
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("查询 queryByPK [{}] error," + this.getClass().getName() + "=[{}]",
                this.getClass().getName(), e.getMessage());
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }
}
